package com.zhengqiangblog.core;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class ActionMapping {

	public static final String DEFAULT_ACTION_METHOD = "execute";
	public static final String DEFAULT_RESULT = "success";

	private String path;
	private RequestMethod method = RequestMethod.ALL;
	private Class<? extends Object> action;
	private String actionMethod = DEFAULT_ACTION_METHOD;
	private Class<? extends Object> actionForm;
	private Map<String, Result> results = new HashMap<String, Result>();
	private List<String> pathVariableNames;

	public ActionMapping() {
	}

	public String getPath() {
		return path;
	}

	public RequestMethod getMethod() {
		return method;
	}

	public Class<? extends Object> getAction() {
		return action;
	}

	public String getActionMethod() {
		return actionMethod;
	}

	public Class<? extends Object> getActionForm() {
		return actionForm;
	}

	public ActionMapping setPath(String path) {
		path = StringUtils.trimToEmpty(path);
		if (MappingHelper.isSlash(path)) {
			path = MappingHelper.SLASH;
		} else {
			// action path SHOULD start with "/"
			if (!MappingHelper.isStartWithSlash(path)) {
				path = MappingHelper.SLASH + path;
			}
			// action path SHOULD NOT end with "/"
			if (MappingHelper.isEndWithSlash(path)) {
				path = path.substring(0, path.length() - 1);
			}
		}
		this.path = path;
		return this;
	}

	public ActionMapping setMethod(RequestMethod method) {
		this.method = method;
		return this;
	}

	public ActionMapping setAction(Class<? extends Object> action) {
		this.action = action;
		return this;
	}

	public ActionMapping setActionMethod(String actionMethod) {
		this.actionMethod = actionMethod;
		return this;
	}

	public ActionMapping setActionForm(Class<? extends Object> actionForm) {
		this.actionForm = actionForm;
		return this;
	}

	public Result getResult(String resultName) {
		return this.results.get(resultName);
	}

	public ActionMapping addResult(String name, String value) {
		Result result = new Result(name, value, ResultType.DISPATCHER);
		this.addResult(result);
		return this;
	}

	public ActionMapping addResult(String name, String value, ResultType resultType) {
		Result result = new Result(name, value, resultType);
		this.addResult(result);
		return this;
	}

	public ActionMapping addResult(Result result) {
		this.results.put(result.getName(), result);
		return this;
	}

	public Map<String, Result> getResults() {
		return results;
	}

	public List<String> getPathVariableNames() {
		return pathVariableNames;
	}

	public void setPathVariableNames(List<String> pathVariableNames) {
		this.pathVariableNames = pathVariableNames;
	}

}
